package martian.m4gic.network.smartfox.core
{
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	import it.gotoandplay.smartfoxserver.data.User;
	
	import martian.m4gic.network.smartfox.core.Fox;
	import martian.m4gic.tools.Domain;
	
	public class Wire
	{
		static public var client:Fox;
		
		
		private var user:User;
		private var id:int;
		private var object:Object;
		private var data:Dictionary;
		
		public function Wire(user:User, object:Object)
		{
			this.user = user;
			this.id = user.getId();
			this.object = object;
			this.data = new Dictionary();
			
			client.addEventListener(Fox.DATA, update);
		}
		
		public function listen(cmd:int, properties:Array = null):void { data[cmd] = properties; }
		public function ignore(cmd:int):void { delete data[cmd]; }
		
		
		
		
		private function update(e:Event):void
		{
			if (!concerned) { return; }
			if (!alive) { destroy(); return; }
			
			var key:String, properties:Array = data[client.data.message.cmd];
				if (properties == null)
				{
					properties = new Array();
					for(key in client.data.message) { properties.push(key); }
				}

			for each(key in properties)
			{
				if (object.hasOwnProperty(key)) { object[key] = client.data.message[key]; }
			}
		}
		
		private function get concerned():Boolean
		{
			for(var cmd:* in data) { if (client.data.message.cmd == parseInt(cmd)) { return true; } }
			return false;
		}
		
		private function get alive():Boolean { return client.room.getUser(id) != null; }
		
		public function destroy():void
		{
			client.removeEventListener(Fox.FRIEND_UPDATE, update);
			
			this.id = 0;
			this.object = null;
			this.data = null;
		}
	}

}